package com.zhongxi.guoyuan.view.play;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.gift.BonusResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.widget.Player;

import java.util.HashMap;
import java.util.Map;

public class VideoActivity extends BaseActivity {

    private SurfaceView surfaceView;
    private SeekBar skbProgress;
    private Player player;
    private TextView tvSec;
    private TimeCount time;
    private boolean type;
    private String urlId;
    private int num = 0;
    private Map<String, String> map = new HashMap<>();
    private String money;
    private String flag;
    private AlertDialog dialog;
    private boolean isAgain;

    /*定义一个倒计时的内部类*/
    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);//参数依次为总时长，和计时的时间间隔
        }

        @Override
        public void onTick(long millisUntilFinished) {//计时过程显示
            tvSec.setText(millisUntilFinished / 1000 + "S后退出广告");
        }

        @Override
        public void onFinish() {//计时完毕时触发
            tvSec.setText(String.valueOf(0));
            if(!type){  //视频播放完,领红包
                flag = "complete";
                map.put("videoid", urlId);
                map.put("bonusamount", MyApplication.getInstance().descsc(money));
                getServer(Url.SPONSORS_WELFARE, map, "", false, null, "post");
            }else{
                if(null!=player){
                    player.stop();
                    player = null;
                }
                finish();
            }
        }

    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try{
            if("complete".equals(flag)){
                BonusResult result = gson.fromJson(response, BonusResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                showShortToast("领取红包成功！");
                Intent intent = new Intent(context, RedPacketActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("status", "1");
                intent.putExtras(bundle);
                setResult(RESULT_OK, intent);
                if(null!=player){
                    player.stop();
                    player = null;
                }
                finish();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse result = gson.fromJson(response, BaseResponse.class);
        if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj()))
            MyApplication.getInstance().setSpValue(result.getSafeobj());
        try{
            if("complete".equals(flag)){
                showShortToast("领取红包失败！");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ad_video);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);  //横屏
        surfaceView = (SurfaceView) this.findViewById(R.id.surfaceView1);
        skbProgress = (SeekBar)this.findViewById(R.id.skbProgress);
        tvSec = (TextView)this.findViewById(R.id.tvSec);  //显示倒计时

        String url = getIntent().getStringExtra("videoUrl");
        urlId = getIntent().getStringExtra("videoId");
        money = getIntent().getStringExtra("money");

        player = new Player(surfaceView, skbProgress, url);

        skbProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, final int progress, boolean fromUser) {
                if(progress>0){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            int duration = player.mediaPlayer.getDuration()/1000;
                            if(0!=duration&&-1!=duration){
                                if(num == 0&&!isAgain){
                                    //duration*(1-progress/100f)  播放的剩余时间换算成秒,+1 是当小数点时 按1来处理
                                    time = new TimeCount((int)(duration*(1-progress/100f)+1)*1000, 1000);  //显示倒计时
                                    time.start();
                                }
                                num++;
                            }
                        }
                    });
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(player != null){
            player.stop();
            player = null;
            if(null!=time)
                time.cancel();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            player.pause();
            isAgain = true;
            if(null!=time){
                time.cancel();
            }
            dialog();
            return false;
        }else{
            return super.onKeyDown(keyCode, event);
        }
    }

    private void dialog() {
        {
            LayoutInflater inflater = LayoutInflater.from(context);
            View view = inflater.inflate(R.layout.dialog_exit,null);
            final AlertDialog.Builder buidler = new AlertDialog.Builder(VideoActivity.this);
            buidler.setView(view);
            buidler.create();
            dialog = buidler.show();

            TextView tvContinue = (TextView) view.findViewById(R.id.tvContinue);
            TextView tvExit = (TextView) view.findViewById(R.id.tvExit);

            tvExit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(player != null){
                        player.stop();
                        player = null;
                    }
                    type = true;
                    flag = "cancel";
                    map.clear();
                    map.put("videoid",urlId);
                    map.put("bonusamount", MyApplication.getInstance().descsc(money));
                    getServer(Url.VIDEO_EXIT, map, "", false, null, "post");
                    Intent intent = new Intent(context, RedPacketActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("status", "0");
                    intent.putExtras(bundle);
                    setResult(RESULT_OK, intent);
                    dialog.dismiss();
                    if(null!=player){
                        player.stop();
                        player = null;
                    }
                    finish();
                }
            });

            tvContinue.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    isAgain = false;
                    player.play();
                    num = 0;
//                    time.start();
                }
            });
        }
    }
}
